********************************************************************************
** 	TITLE:		de2009_polls		                                          ** 	
**	AUTHOR:	    Philippe Mongrain                                             **
**	DATE:		October 2022 					                              **	
**  VERSION:	Stata 16					                                  **	
********************************************************************************

* Version control

version 16.0

* Import data

use "LONG_MI_NATURE_20180111.dta", clear

keep if elecdate == td(27sep2009) & country == "Germany" & election == "Legislative"

* Generate survey date

format %tdMon_DD,_CCYY polldate

* Generate election date

format %tdMon_DD,_CCYY elecdate

rename elecdate electiondate

* Time of survey

gen time = (electiondate - polldate)

drop if time == 0

* Keep and order needed variables

keep polldate electiondate party poll_ time

rename poll_ vote

order polldate electiondate time party vote

* Generate rank of parties

drop if vote == .

gsort polldate -vote

bysort polldate : gen rank = _n

gen first = party if rank == 1
gen second = party if rank == 2
gen third = party if rank == 3

bysort polldate : gen winner = first[1]
bysort polldate : gen runnerup = second[2]
bysort polldate : gen thirdplace = third[3]

* Generate poll margin

bysort polldate : gen pollmar = vote[1] - vote[2]

* Drop duplicates

duplicates tag polldate, gen(dup)
duplicates drop polldate, force
drop dup

* Misleading poll

gen misleading = 0 if winner == 1 & pollmar >= 1
replace misleading = 1 if misleading!=0

* Save

drop if time == 0 | time == .

keep polldate pollmar misleading time

save "de2009_polls.dta", replace